const axios = require('axios');
const { generateSign } = require('../utils/xianyuUtils');

class XianyuApis {
    constructor() {
        this.baseUrl = 'https://h5api.m.goofish.com';
        this.defaultHeaders = {
            'accept': 'application/json',
            'accept-language': 'zh-CN,zh;q=0.9',
            'cache-control': 'no-cache',
            'origin': 'https://www.goofish.com',
            'pragma': 'no-cache',
            'priority': 'u=1, i',
            'referer': 'https://www.goofish.com/',
            'sec-ch-ua': '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-site',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36',
        };
    }

    /**
     * 获取访问令牌
     * @param {Object} cookies Cookie对象
     * @param {string} deviceId 设备ID
     * @returns {Promise<Object>} 令牌响应
     */
    async getToken(cookies, deviceId) {
        try {
            const timestamp = Date.now();
            const dataVal = JSON.stringify({
                appKey: "444e9908a51d1cb236a27862abc769c9",
                deviceId: deviceId
            });

            const params = {
                jsv: '2.7.2',
                appKey: '34839810',
                t: timestamp.toString(),
                sign: '',
                v: '1.0',
                type: 'originaljson',
                accountSite: 'xianyu',
                dataType: 'json',
                timeout: '20000',
                api: 'mtop.taobao.idlemessage.pc.login.token',
                sessionOption: 'AutoLoginOnly',
                spm_cnt: 'a21ybx.im.0.0',
            };

            // 生成签名
            const token = cookies['_m_h5_tk'] ? cookies['_m_h5_tk'].split('_')[0] : '';
            const sign = generateSign(params.t, token, dataVal);
            params.sign = sign;

            const response = await axios.post(
                `${this.baseUrl}/h5/mtop.taobao.idlemessage.pc.login.token/1.0/`,
                { data: dataVal },
                {
                    params,
                    headers: this.defaultHeaders,
                    cookies
                }
            );

            return response.data;
        } catch (error) {
            console.error('获取令牌失败:', error.message);
            throw error;
        }
    }

    /**
     * 发送HTTP请求到闲鱼API
     * @param {string} endpoint API端点
     * @param {Object} data 请求数据
     * @param {Object} cookies Cookie对象
     * @param {Object} options 其他选项
     * @returns {Promise<Object>} API响应
     */
    async makeRequest(endpoint, data, cookies, options = {}) {
        try {
            const timestamp = Date.now();
            const dataStr = JSON.stringify(data);
            
            const params = {
                jsv: '2.7.2',
                appKey: '34839810',
                t: timestamp.toString(),
                sign: '',
                v: '1.0',
                type: 'originaljson',
                accountSite: 'xianyu',
                dataType: 'json',
                timeout: '20000',
                ...options.params
            };

            // 生成签名
            const token = cookies['_m_h5_tk'] ? cookies['_m_h5_tk'].split('_')[0] : '';
            const sign = generateSign(params.t, token, dataStr);
            params.sign = sign;

            const response = await axios.post(
                `${this.baseUrl}${endpoint}`,
                { data: dataStr },
                {
                    params,
                    headers: { ...this.defaultHeaders, ...options.headers },
                    cookies
                }
            );

            return response.data;
        } catch (error) {
            console.error('API请求失败:', error.message);
            throw error;
        }
    }
}

module.exports = XianyuApis;
